<template>
  <div>
    <ckeditor ref="ckeditor" v-model="editorData" :type="type" :config="config" @ready="onEditorReady"
      :read-only="readOnly" @input="onEditorInput" :throttle="120" :editor-url="editorUrl"></ckeditor>
  </div>
</template>

<script>
  import { getToken } from "@/utils/auth";
  import CKEditor from "ckeditor4-vue";
  export default {
    components: {
      ckeditor: CKEditor.component
    },
    name: "CKEditor",
    props: {
      /* 编辑器的内容 */
      value: {
        type: String,
        default: "",
      },
      /* 高度 */
      height: {
        type: Number,
        default: null,
      },
      /* 最小高度 */
      minHeight: {
        type: Number,
        default: null,
      },
      // 富文本类型两种（classic）和（inline）
      isInline: {
        type: Boolean,
        default: false
      },
      /* 只读 */
      readOnly: {
        type: Boolean,
        default: false,
      },
      config: {
        type: Object,
        default: () => {
          return {
            editorplaceholder: "请输入内容",
            // 工具栏
            toolbarGroups: [
              { name: "document", groups: ["mode", "document", "doctools"] },
              { name: "clipboard", groups: ["clipboard", "undo"] },
              {
                name: "editing",
                groups: ["find", "selection", "spellchecker", "editing"]
              },
              { name: "forms", groups: ["forms"] },
              { name: "basicstyles", groups: ["basicstyles", "cleanup"] },
              {
                name: "paragraph",
                groups: ["list", "indent", "blocks", "align", "bidi", "paragraph"]
              },
              { name: "links", groups: ["links"] },
              { name: "insert", groups: ["insert"] },
              { name: "styles", groups: ["styles"] },
              { name: "colors", groups: ["colors"] },
              { name: "tools", groups: ["tools"] },
              { name: "others", groups: ["others"] },
              { name: "about", groups: ["about"] }
            ],
            //   extraPlugins: "notification",
            //   // toolbar 中的一些配置功能 需要在这里添加一下才可以用 例如 print colorbutton
            extraPlugins:
              "print,format,font,colorbutton,justify,uploadimage,notification,quicktable,autogrow,addpic",
            removeDialogTabs: "image:advanced;link:advanced",
            removePlugins: "image",
            // 本地图片上传(ckeditor官网有解释)
            filebrowserImageUploadUrl: process.env.VUE_APP_BASE_API + "/file/upload",
            filebrowserUploadUrl: process.env.VUE_APP_BASE_API + "/file/upload",
            // cloudServices_uploadUrl: process.env.VUE_APP_BASE_API + "/file/upload",
            // 删除的工具栏
            // removeButtons:"Source,Save,NewPage,ExportPdf,Preview,Print,Templates,Cut,Copy,Paste,PasteText,PasteFromWord,Undo,Redo,Replace,Find,SelectAll,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Subscript,Superscript,CopyFormatting,Outdent,Indent,CreateDiv,Blockquote,BidiLtr,BidiRtl,Language,Unlink,Link,Anchor,HorizontalRule,Smiley,SpecialChar,PageBreak,Iframe,ShowBlocks,About,FontSize,Font"
            removeButtons: "Source,Save,NewPage,ExportPdf,Preview,Print,Templates,Cut,Copy,Paste,PasteText,PasteFromWord,ImageButton,Iframe,ShowBlocks,About,Form"
          };
        },
      },
      ckeditor:null,
    },
    data() {
      return {
        editorUrl: "/ckeditor/ckeditor.js", //将指令的值更改为指向所需的 CKEditor 4 脚本位置来更改
        uploadUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken()
        },
        editorData: "",
      };
    },
    computed: {
      type() {
        return this.isInline ? "inline" : "classic";
      }
    },
    watch: {
      value: {
        handler(val) {
            console.log("value",val);
            this.editorData = val == null ? "" : val;
            console.log("editorData",this.editorData);
        },
        immediate: true,
      },
    },
    beforeDestroy() {
      // const editor = this.$refs.ckeditor.instance
      // console.log("CKEDITOR初始化");
      // editor.destroy();
    },
    methods: {
      onEditorReady() {
        // console.log("CKEDITOR初始化" ,this.$refs.ckeditor.instance.getData());
        const editor = this.$refs.ckeditor.instance
     
        //监听ready 事件
        // editor.on("instanceReady", function(evt) {
        //   console.log("CKEDITOR初始化完成",evt);
        // });
        // //监听change 事件
        // editor.on("change", function(evt) {
        //   console.log("CKEDITOR内容改变");
        // });
        // //监听blur 事件
        // editor.on("blur", function(evt) {
        //   console.log("CKEDITOR失去焦点");
        // });
        // //监听focus 事件
        // editor.on("focus", function(evt) {
        //   console.log("CKEDITOR获得焦点");
        // });
        // //监听paste 事件
        // editor.on("paste", function(evt) {
        //   console.log("CKEDITOR粘贴");
        // });
        // //监听selectionChange 事件
        // editor.on("selectionChange", function(evt) {
        //   console.log("CKEDITOR选区改变");
        // });
        // //监听key 事件
        // editor.on("key", function(evt) {
        //   console.log("CKEDITOR按键");
        // });
        // //监听keyup 事件
        // editor.on("keyup", function(evt) {
        //   console.log("CKEDITOR按键弹起");
        // });
        // //监听keydown 事件
        // editor.on("keydown", function(evt) {
        //   console.log("CKEDITOR按键按下");
        // });
        // //监听keypress 事件
        // editor.on("keypress", function(evt) {
        //   console.log("CKEDITOR按键按下");
        // });
        // //监听contentDom 事件
        // editor.on("contentDom", function(evt) {
        //   console.log("CKEDITOR内容DOM加载完成");
        // });
        // this.ckeditor = this.$refs.ckeditor;
        editor.on('fileUploadRequest', function (evt) {
          console.log("上传图片", evt);
          const formData = new FormData()
          const fileLoader = evt.data.fileLoader
          const { xhr, uploadUrl, file, fileName } = fileLoader
          xhr.open('post', uploadUrl)
          // 这里可以根据自己需要添加token等其他头信息
          xhr.setRequestHeader('Authorization', "Bearer " + getToken())
          formData.append('file', file, fileName)
          xhr.send(formData)
          evt.stop()
        })
        editor.on('fileUploadResponse', function (evt) {
          evt.stop()
          const xhr = evt.data.fileLoader.xhr
          const res = JSON.parse(xhr.responseText)
          // 自己处理返回逻辑
          if (res.code !== 200) {
            evt.data.message = res.msg
            evt.cancel()
          } else {
            evt.data.url = res.data.url
          }
        })
      },
      onEditorInput(val) {
        console.log("CKEDITOR输入", val);
        this.$emit("input", val);
      }
    },
  }
</script>

<style>

</style>